package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.adapter.WarrantyAdapter;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.WarrantiesTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.service.UpdateWarrantyService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.JSONParser;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class FindWarranityActivity extends Activity implements Receiver, AsyncQueryListener, OnItemClickListener {

	private ListView listView;
	private WarrantyAdapter warrantyAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private DetachableResultReceiver receiver;
	private static SharedPreferences prefs;
	private String accountId;
	private EditText mask;
	private ProgressBar progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_warranity);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		accountId = prefs.getString(Keys._accountId, "");

		mask = (EditText) findViewById(R.id.mask);
		progress = (ProgressBar) findViewById(R.id.progress_loading);

		mask.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				showResults(TextUtils.isEmpty(s) ? null : s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		listView = (ListView) findViewById(R.id.warranty_list);
		listView.setOnItemClickListener(this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		showResults(null);

		// find warranties
		Intent warrantyByAccountIdIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateWarrantyService.class);
		warrantyByAccountIdIntent.putExtra(UpdateWarrantyService.EXTRA_STATUS_RECEIVER, receiver);
		warrantyByAccountIdIntent.putExtra(UpdateWarrantyService.EXTRA_REQUEST_CODE, QueriesCodes.WARRANTY_BY_ACCOUNT_ID);
		startService(warrantyByAccountIdIntent);

		// Upload account warranty
		Intent testIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateWarrantyService.class);
		testIntent.putExtra(UpdateWarrantyService.EXTRA_STATUS_RECEIVER, receiver);
		testIntent.putExtra(UpdateWarrantyService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID);
		startService(testIntent);

		// handleIntent(getIntent());

	}

	@Override
	protected void onResume() {
		super.onResume();
		showResults(TextUtils.isEmpty(mask.getText().toString()) ? null : mask.getText().toString());
	}

	private void retrieveWarrantyById(String id) {
		String[] projectionWarranty = { WarrantiesTable._ID, WarrantiesTable.WARRANTY_ID, WarrantiesTable.PRODUCT_PRICE, WarrantiesTable.LIST_LABEL, WarrantiesTable.IMAGE_URL,
				WarrantiesTable.WARRANTY_TYPE };
		mHandler.startQuery(QueriesCodes.WARRANTY_BY_UNIQUE, WarrantiesTable.CONTENT_URI, projectionWarranty, WarrantiesTable._ID + " = " + "'" + id + "'", null, WarrantiesTable.LIST_LABEL);
	}

	private void showResults(String queryMask) {
		String selection;
		if (queryMask != null)
			selection = WarrantiesTable.LIST_LABEL + " LIKE '%" + queryMask + "%' AND " + WarrantiesTable.ACCOUNT_ID + " = " + "'" + accountId + "'";
		else
			selection = WarrantiesTable.ACCOUNT_ID + " = " + "'" + accountId + "'";

		String[] projectionWarranty = { WarrantiesTable._ID, WarrantiesTable.WARRANTY_ID, WarrantiesTable.PRODUCT_PRICE, WarrantiesTable.LIST_LABEL, WarrantiesTable.IMAGE_URL,
				WarrantiesTable.WARRANTY_TYPE };
		mHandler.startQuery(QueriesCodes.WARRANTY_BY_ACCOUNT_ID_SEARCH, WarrantiesTable.CONTENT_URI, projectionWarranty, selection, null, null);
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			progress.setVisibility(View.VISIBLE);
			break;
		case UpdateIntentService.STATUS_ERROR:
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			progress.setVisibility(View.GONE);
			break;
		case UpdateIntentService.STATUS_FINISHED:
			showResults(null);
			if (resultData.containsKey(Keys.actionIdentificator) && resultData.getInt(Keys.actionIdentificator) == QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID) {
				progress.setVisibility(View.GONE);
			}
			break;
		}
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.WARRANTY_BY_ACCOUNT_ID_SEARCH:
			if (cursor != null /* && isSearchActive */) {
				startManagingCursor(cursor);
				// when db is empty show dialog box
				// if (cursor.getCount() == 0 && progress == null)
				// progress = ProgressDialog.show(this,
				// getString(R.string.loading), getString(R.string.please_wait),
				// true, false);

				if (warrantyAdapter == null) {
					warrantyAdapter = new WarrantyAdapter(this, cursor);
					listView.setAdapter(warrantyAdapter);
				} else {
					warrantyAdapter.changeCursor(cursor);
					warrantyAdapter.notifyDataSetChanged();
				}
			}
			break;
		case QueriesCodes.WARRANTY_BY_UNIQUE:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					int type = cursor.getInt(cursor.getColumnIndex(WarrantiesTable.WARRANTY_TYPE));
					String id = cursor.getString(cursor.getColumnIndex(WarrantiesTable.WARRANTY_ID));
					Intent detailWarrantyIntent = null;
					switch (type) {
					case JSONParser.IS_OWN_WARRANTY:
						detailWarrantyIntent = new Intent(getApplicationContext(), WarrantyDetailActivity.class);
						break;
					case JSONParser.IS_ACCOUNT_UPLOAD_WARRANTY:
						detailWarrantyIntent = new Intent(getApplicationContext(), UploadActivity.class);
						detailWarrantyIntent.putExtra(Keys._isuploaded, true);
						detailWarrantyIntent.putExtra(Keys._advancedPopup, true);

						break;

					default:
						break;
					}
					detailWarrantyIntent.putExtra(Keys._warrantyId, id);
					startActivity(detailWarrantyIntent);
				}
				cursor.close();
			}

			break;

		default:
			break;

		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id1) {
		retrieveWarrantyById(String.valueOf(id1));

	}

}